import xml.etree.ElementTree as ET
import re, sys

if len(sys.argv)!=3:
    sys.exit()

java_file = sys.argv[1]
mapper_xmlfile = sys.argv[2]

# java_file = 'D:/Code/_my/resell/modules/resell-backend/resell-common/src/main/java/com/dyys/edu/monitor/mapper/LoginLogMapper.java'
# mapper_xmlfile = "D:/Code/_my/resell/modules/resell-backend/resell-auth/src/main/resources/mapper/system/LoginLogMapper.xml"

content = ''
with open(java_file, 'r', encoding='utf-8') as f:
    content = f.read()

tree = ET.parse(mapper_xmlfile)
root = tree.getroot()

methods = {}
for sn in root:
    id = sn.attrib['id']
    if sn.tag=='select':
        xml_txt = ET.tostring(sn, encoding='unicode').strip()
        xml_txt = re.sub('<select .*?>', "@Select('''<script>", xml_txt)
        xml_txt = xml_txt.replace('</select>', "</script>''')")
        methods[id] = xml_txt

    elif sn.tag=='update':
        xml_txt = ET.tostring(sn, encoding='unicode').strip()
        xml_txt = re.sub('<update .*?>', "@Update('''<script>", xml_txt)
        xml_txt = xml_txt.replace('</update>', "</script>''')")
        methods[id] = xml_txt

    elif sn.tag=='delete':
        xml_txt = ET.tostring(sn, encoding='unicode').strip()
        xml_txt = re.sub('<delete .*?>', "@Delete('''<script>", xml_txt)
        xml_txt = xml_txt.replace('</delete>', "</script>''')")
        methods[id] = xml_txt

    elif sn.tag=='insert':
        xml_txt = ET.tostring(sn, encoding='unicode').strip()
        xml_txt = re.sub('<insert .*?>', "@Insert('''<script>", xml_txt)
        xml_txt = xml_txt.replace('</insert>', "</script>''')")
        methods[id] = xml_txt

for k,v in methods.items():
    try:
        begin=0
        end = 0
        while True:
            begin = content.index(k, end)
            end = begin+len(k)
            c = content[end]
            if not c.isalnum():
                p2 = content.rindex('\n', 0, begin)
                content = content[:p2] + '\n\t'+ v + content[p2:]
                break
    except ValueError:
        pass

groovy_file = java_file[:java_file.rindex('.')] + ".groovy"

with open(groovy_file, 'w', encoding='utf-8') as f:
    f.write(content)
